package com.qf.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Web相关工具类，用于获取请求信息
 * @USER: Administrator
 * @DATE: 2025/9/5 下午7:24
 * @VERSION: 1.0.0
 */
public class WebUtils {

    /**
     * 未知的字符串常量，用于表示未知或未设置的值。
     */
    private static final String UNKNOWN = "unknown";

    /**
     * 获取用户真实IP地址（兼容代理场景）
     */
    public static String getIpAddress(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }

        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            // 本地访问时，IP可能为0:0:0:0:0:0:0:1，转换为127.0.0.1
            if ("0:0:0:0:0:0:0:1".equals(ipAddress)) {
                try {
                    ipAddress = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e) {
                    // 忽略异常
                }
            }
        }

        // 多级代理时，x-forwarded-for可能返回多个IP，取第一个非unknown的IP
        if (ipAddress != null && ipAddress.contains(",")) {
            String[] ips = ipAddress.split(",");
            for (String ip : ips) {
                if (!"unknown".equalsIgnoreCase(ip.trim())) {
                    ipAddress = ip.trim();
                    break;
                }
            }
        }
        return ipAddress;
    }

    /**
     * 获取用户代理信息（浏览器/操作系统）
     */
    public static String getUserAgent(HttpServletRequest request) {
        if (request == null) {
            return "";
        }
        return request.getHeader("User-Agent");
    }


    /**
     * 获取当前会话ID
     */
    public static String getSessionId(HttpServletRequest request) {
        if (request == null) {
            return "";
        }
        HttpSession session = request.getSession(false); // 不存在时不创建新会话
        return session != null ? session.getId() : "";
    }

}
